from flask import g
from flask import session, jsonify

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from . import index_blu
from flask import render_template, current_app



@index_blu.route("/", methods=['GET', 'POST'])
@user_login_data
def work():
    # 取出session中的用户编号
    # user_id = session.get('user_id')
    #
    # # 取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 处理热门新闻,查询前10条
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
    # 将新闻对象列表,转成字典列表
    click_news_list = []
    for news in click_news:
        click_news_list.append(news.to_dict())

    # 获取分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

        # 将对象分类列表转成,字典列表
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    # 将用户对象信息转成字典信息
    data = {'user_info': g.user.to_dict() if g.user else None,
            'click_news_list':click_news_list,
            'categories_list':categories_list
            }



    return render_template('news/index.html', data=data)



@index_blu.route("/favicon.ico")
def web_log():
    return current_app.send_static_file('news/favicon.ico')